package com.bipa.service;

import com.bipa.bean.Order;
import com.bipa.bean.OrderItem;
import com.bipa.dao.ArticleDao;
import com.bipa.dao.OrderDao;
import com.bipa.util.PagerModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service("orderService")
public class OrderService {

    @Autowired
    OrderDao orderDao;

    @Autowired
    ArticleDao articleDao;

    //保存订单信息
    public void saveOrder(String totalMoney, String aId_buyNum,int userId){
        Order order = new Order();
        order.setAmount(Double.valueOf(totalMoney));
        order.setCreate_date(new Date());
        String orderNo = UUID.randomUUID().toString();

        order.setOrder_code(orderNo);
        order.setUser_id(userId);

        //保存订单信息 并获取订单的主键值
        int id = orderDao.saveOrder(order);
        id = order.getId();
        String[] ids = aId_buyNum.split(",");
        for(String info : ids) {
            String[] id_num = info.split("_");
            /*OrderItem item = new OrderItem();
            item.setArticle_id(Integer.valueOf(id_num[0]));
            item.setOrder_num(Integer.valueOf(id_num[1]));
            item.setOrder_id(id);*/
            //保存订单明细
            orderDao.saveItem(id,Integer.valueOf(id_num[0]),Integer.valueOf(id_num[1 ]));
        }
    }

    //根据用户id获取当前用户的订单信息
    public List<Order> getOrdersByUserId(int id){
        //1、根据用户的id查询订单表（ec_order）
        List<Order> orders = orderDao.getOrdersByUserId(id);
        //2、根据订单id查询订单详情表需要获取商品id以及购买数量
        for(Order order : orders) {
            List<OrderItem> items = orderDao.getItemsByOrderId(order.getId());
            for (OrderItem orderItem : items){
                orderItem.setArticle(articleDao.getArticleById(orderItem.getArticle_id() ));
            }

            //将订单详情封装至订单中
            order.setItems(items);
        }

        return orders;
    }

    public int getAll(String payStatus,String ordeCode){
        return orderDao.getAll(payStatus,ordeCode).size();
    }

    public List<Order> findAllOrders(PagerModel pagerModel,String paystatus,String order_code){
        List<Order> orders = orderDao.findAllOrders(paystatus,order_code,pagerModel.getStartSize(),pagerModel.getPageSize());
        for(Order order : orders){
            List<OrderItem> items = orderDao.getItemsByOrderId(order.getId());
            for (OrderItem orderItem : items){
                orderItem.setArticle(articleDao.getArticleById(orderItem.getArticle_id()));
            }
            order.setItems(items);
        }
        return orders;
    }

    public void checkOrder(Integer id,Integer status){

        orderDao.checkOrder(id,status,status==0 ? null : new Timestamp(new Date().getTime()));
    }
}
